<template>
	<div>
		<div class="table-title bor-botm-dashed">
			<ul>
				<!--<li>
						<input type="text" readonly="readonly"/>
					</li>-->
				<li>
				</li>
				<!--<ul v-if="opinionOrExplain == false" class="dis-in-block">
						<li>审批：
							<el-select name="" v-model="opinion">
								<el-option v-for="item in opinionData" :label="item.label" :key="item.value" :value="item.value"></el-option>
							</el-select>
						</li>
						<li v-if="opinion == '不同意'">流转：
							<el-select name="" v-model="circulation">
								<el-option v-for="item in circulationDate" :label="item.label" :key="item.value" :value="item.value"></el-option>
							</el-select>
						</li>
					</ul>-->

			</ul>
			<el-form :inline="true" class="demo-form-inline">
				<el-row>
					<el-col>
						<p>处理意见：</p>
						<el-input type="textarea" v-model="describe" :rows="4" readonly="readonly"></el-input>
					</el-col>
				</el-row>
			</el-form>

		</div>

		<div class="process-information">
			<el-row>
				<el-col>
					<h1>流程信息：</h1>
				</el-col>
			</el-row>
			<div class="process-information-body">
				<el-row :gutter="20">
					<el-col :span="12">
						名称：<span>{{processInfo.name}}</span>
					</el-col>
					<el-col :span="12">
						发起人：<span>{{processInfo.Initiator}}</span>
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="12">
						发起时间：<span>{{processInfo.startTime}}</span>
					</el-col>
					<el-col :span="12">
						流程定义名称：<span>{{processInfo.definitionName}}</span>
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="12">
						流程状态：
						<span v-if="processInfo.state == true">运行中</span>
						<span v-if="processInfo.state == false">非运行中</span>
					</el-col>
					<el-col :span="12">
						优先级：<span>{{processInfo.priority}}</span>
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="12">
						处理时长：
						<span>{{processInfo.durationInMillis}}</span>
					</el-col>
					<el-col :span="12">
						结束时间：<span>{{processInfo.endTime}}</span>
					</el-col>
				</el-row>
			</div>
		</div>

		<div class="rendering-form" id="huoduan_frame">
			<div v-if="formData.length>0" v-for="(item,index) in formData">
				<iframe frameborder="0" :id="item.id" :src="item.url" width="100%"></iframe>
			</div>
		</div>
		<div class="step">
			<el-row :gutter=20>
				<el-col :span="6" v-for="item in seeForm">
					<el-card>
						<div class="text item">
							{{'审批人 ' +item.assignee }}
						</div>
						<div class="text item" v-if="item.descKey!=null">
							{{'处理意见 ' +item.descKey }}
						</div>
						<div class="text item" v-else>
							{{'处理意见 ' }}
						</div>
						<div class="text item">
							{{'审批时间 ' +item.endTime }}
						</div>
						<div class="text item">
							{{'处理时长 ' +item.durationInMillis }}
						</div>
						<div class="text item">
							{{'任务创建时间 ' +item.startTime }}
						</div>
						<div class="bottom clearfix">
							<el-button type="primary" @click="viewForm(item)" v-if="item.isShow==true">查看表单</el-button>
							<el-button type="primary" @click="seeEnclosure" v-if="item.atmount>0">查看附件</el-button>
						</div>
					</el-card>
				</el-col>
			</el-row>

		</div>
		
		<el-dialog title="查看表单" :visible.sync="dialogVisible" width="90%" :before-close="handleClose">
          <div id="dialog-form">
          	<div v-for="item in diaFormData">
					<!--<p>{{item.url}}</p>-->
					<iframe frameborder="0" :id="item.id" :src="item.url" width="100%" @load="diaLoad"></iframe>
				</div>
          </div>
			

			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="dialogVisible = false">确 定</el-button>
			</span>
		</el-dialog>

		<el-dialog title="查看附件" :visible.sync="uploadVisible" width="90%" :before-close="handleClose">
			<ul>
				<h2>已上传</h2>
				<li v-if="formUpload.length>0" v-for="item in formUpload">
					<!--v-for="item in attachments  {{item.name}}"-->
					<span>{{item.name}}</span>
					<!--<span><el-button type="danger">删除</el-button></span>-->
				</li>
			</ul>
			<span slot="footer" class="dialog-footer">
    <el-button @click="uploadVisible = false">取 消</el-button>
    <el-button type="primary" @click="uploadVisible = false">确 定</el-button>
  </span>
		</el-dialog>

		<el-row>
			<el-col :span="24">
				<div class="already-upload">
					<ul>
						<h2>已上传</h2>
						<li>
							<!--v-for="item in attachments  {{item.name}}"-->
							<span>shedeh</span>
							<!--<span><el-button type="danger">删除</el-button></span>-->
						</li>
					</ul>
				</div>
			</el-col>
		</el-row>
	</div>
</template>

<script>
	export default {
		name: 'handle',
		data() {
			return {
				describe: '',
				processInfo: {
					name: '',
					approvalOpinion: '',
					Initiator: '',
					startTime: '',
					definitionName: '',
					state: '',
					priority: '',
				},
				formData: [],
				seeForm: [],
				ifrmUrl: [],
				processInstanceId: '',
				taskInstanceId: '',
				processDefinitionId: '',
				taskDefKey: '',
				hasHisFormData: false,
				executionId: '',
				iframeData: [],
				taskDefinitionKey: '',
				initFormData: [],
				attachments: [], //附件
				dialogVisible: false,
				hisFrmData: [],
				formUpload: [],
				uploadVisible: false,
				diaFormData: [],
			}
		},
		mounted: function() {
			var vm = this
			console.log(localStorage.getItem('taskInstanceId'));
			console.log(localStorage.getItem('processInstanceId'));
			console.log(localStorage.getItem('processDefinitionId'));
			//			vm.taskInstanceId = "645052";
			//			vm.processInstanceId = "645042"
			//			vm.processDefinitionId = "workflow-test-01:3:175008"
			vm.taskInstanceId = localStorage.getItem('taskInstanceIds');
			vm.processInstanceId = localStorage.getItem('processInstanceIds');
			vm.processDefinitionId = localStorage.getItem('processDefinitionIds')
			var dataT = {
				processInstanceId: vm.processInstanceId,
				taskInstanceId: vm.taskInstanceId
			};
			//查询工作流测试借口
			this.$http.post('http://localhost/act/taskInstance/getTaskInstanceView?processInstanceId=' + vm.processInstanceId + "&taskInstanceId=" + vm.taskInstanceId).
			then(function(data) {
				if(data.data.messageCode != 0) {
					console.log(data)
					vm.$message({
						message: data.data.message,
						type: 'error'
					});
					return;
				}
				vm.taskDefinitionKey = data.data.object.taskEntity.taskDefinitionKey
				vm.taskDefKey = data.data.object.taskDefKey
				vm.executionId = data.data.object.taskEntity.executionId
				Date.prototype.Format = function(fmt) { //author: meizz 
					var o = {
						"M+": this.getMonth() + 1, //月份 
						"d+": this.getDate(), //日 
						"h+": this.getHours(), //小时 
						"m+": this.getMinutes(), //分 
						"s+": this.getSeconds(), //秒 
					};
					if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
					for(var k in o)
						if(new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
					return fmt;
				} //转换后端的日期格式
				vm.describe = data.data.object.descKey
				vm.processInfo.name = data.data.object.processInstance.name;
				vm.processInfo.Initiator = data.data.object.processInstance.startUserId;
				vm.processInfo.startTime = new Date(data.data.object.processInstance.startTime).Format("yyyy-MM-dd hh:mm:ss");
				vm.processInfo.definitionName = data.data.object.processInstance.processDefinitionName;
				vm.processInfo.state = data.data.object.processInstance.active;
				vm.processInfo.priority = data.data.object.processInstance.processPriority;
				vm.hasHisFormData = data.data.object.hasHisFormData
				var formKey = data.data.object.taskEntity.formKey;
				if(formKey != null) {
					var formName = formKey.split(",")
				}
				//根据上个借口得知几个表单 然后拿到请求表单 通过iframe打开
				//				console.log(formName.length)
				if(formName != undefined && formName.length != 0) {
					for(var i = 0; i < formName.length; i++) {
						vm.$http.get('http://localhost/activiti-web/activitiTemplate/' + formName[i] + "?processInstanceId=" + vm.processInstanceId + "&&taskInstanceId=" + vm.taskInstanceId).then(
							function(data) {
								var url = {};
								url.url = data.config.url;
								var ifraUrlstart = data.config.url.lastIndexOf('/');
								var ifraUrlend = data.config.url.indexOf('.');
								url.id = data.config.url.substring(ifraUrlstart + 1, ifraUrlend)
								vm.formData.push(url)
							},
							function(error) {
								vm.$message.error(data.data.message);
							}
						)
					}
				}

			}, function(error) {
//				vm.$message.error(data.data.message);
			});

			this.$http.post('http://localhost/act/taskInstance/getHisTaskInstances?processInstanceId=' + vm.processInstanceId).then(function(data) {
				vm.seeForm = data.data.data
				Date.prototype.Format = function(fmt) { //author: meizz 
					var o = {
						"M+": this.getMonth() + 1, //月份 
						"d+": this.getDate(), //日 
						"h+": this.getHours(), //小时 
						"m+": this.getMinutes(), //分 
						"s+": this.getSeconds(), //秒 
					};
					if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
					for(var k in o)
						if(new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
					return fmt;
				} //转换后端的日期格式
				for(var i = 0; i < vm.seeForm.length; i++) {
					vm.seeForm[i].startTime = new Date(vm.seeForm[i].startTime).Format("yyyy-MM-dd hh:mm:ss");
					vm.seeForm[i].endTime = new Date(vm.seeForm[i].startTime).Format("yyyy-MM-dd hh:mm:ss");
					var durationInMillis = vm.seeForm[i].durationInMillis
					vm.seeForm[i].durationInMillis = formatSeconds(durationInMillis)
					if(vm.seeForm[i].formKey != null) {
						vm.seeForm[i].isShow = true;
					} else {
						vm.seeForm[i].isShow = false
					}
				};

				function formatSeconds(date3) {
					var days = Math.floor(date3 / (24 * 3600 * 1000))

					//计算出小时数
					var leave1 = date3 % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
					var hours = Math.floor(leave1 / (3600 * 1000))
					//计算相差分钟数
					var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
					var minutes = Math.floor(leave2 / (60 * 1000))
					//计算相差秒数
					var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
					var seconds = Math.round(leave3 / 1000)
					var result = "";
					if(days > 0) {
						result += days + "天";
					}
					if(hours > 0) {
						result += hours + "小时";
					}
					if(minutes > 0) {
						result += minutes + "分钟";
					}
					if(seconds > 0) {
						result += seconds + "秒";
					}
					return result;
				};
			}, function(error) {

			});
			//查询临时保存的上传附件
			this.$http.post('http://localhost/act/taskInstance/getTaskAttachments?processInstanceId=' + vm.processInstanceId + "&&taskId=" + vm.taskInstanceId).then(
				function(data) {
					console.log(data)
					vm.formUpload = data.data
				},
				function(error) {
					vm.$message.error(data.data.message);
				}
			)

		},
		watch: {
			formData: function(val) {
				var vm = this
				setTimeout(function() {
					$('#huoduan_frame iframe').each(function() {
						$(this).contents().find('body form input').attr("disabled", true)
						$(this).contents().find('body form select').attr("disabled", true)
						console.log(vm.initFormData)
						for(var i = 0; i < vm.initFormData.length; i++) {
							var id = vm.initFormData[i].formKey.indexOf('.');
							var iframrId = vm.initFormData[i].formKey.substring(0, id)
							if($(this).attr('id') == iframrId) {
								var formeD = vm.initFormData[i].formData.split("&")
								var obj = {};
								for(var i = 0; i < formeD.length; i++) {
									var arr = formeD[i].split('=');
									obj[arr[0]] = arr[1];
								}
								for(var key in obj) {
									$(this).contents().find('body form input[name=' + key + ']').val(obj[key])
									$(this).contents().find('body form input[type=radio][name=' + key + ']').attr("checked", obj[key])
									$(this).contents().find('body form input[type=checkbox][name=' + key + ']').attr("checked", obj[key])
									$(this).contents().find('body form select[name=' + key + ']').val(obj[key])
								}
							}
						}
						$(this).height($(this).contents().find('body').height() + 20);
					
					})

				}, 500)
			},


			//			opinion:function(val){
			//				return this.describe = val
			//			}
		},
		methods: {
			preservation(type) {
				var iframeData = [];
				var vm = this;
				var transition = {};
				for(var i = 0; i < vm.circulationDate.length; i++) {
					if(vm.circulation == vm.circulationDate[i].value) {
						transition.key = vm.circulationDate[i].lable;
					}
				}
				$('#huoduan_frame iframe').each(function() {
					var iframeDataObj = {
						processInstanceId: vm.processInstanceId,
						taskInstanceId: vm.taskInstanceId,
						formKey: $(this).attr('id') + '.form',
						processDefinitionId: vm.processDefinitionId,
						taskDefKey: vm.taskDefKey,
						formData: $(this).contents().find("form").serialize(),
						taskDefKey: vm.taskDefinitionKey,
					}
					vm.iframeData.push(iframeDataObj)
				})
				var dataT = {
					processInstanceId: vm.processInstanceId,
					transitionKey: transition.key,
					transitionValue: vm.circulation,
					processDefiniitonId: vm.processDefinitionId,
					executionId: vm.executionId,
					taskInstanceId: vm.taskInstanceId,
					formOpt: type,
					desc: vm.describe,
					forms: vm.iframeData
				}
				this.$http.post('http://localhost/act/taskInstance/completeTaskInstance',
					dataT
				).then(function(data) {
					vm.iframeData = [];
					console.log(data.data)
					if(data.data.messageCode != 0) {
						vm.$message({
							message: data.data.message,
							type: 'error'
						});
					} else {
						vm.$message({
							message: data.data.message,
							type: 'error'
						});
					}
				}, function(error) {
					vm.$message.error(data.data.message);
				})

			},
			viewForm(item) {
				console.log(item)
				var vm = this;
				vm.diaFormData = [];
				vm.dialogVisible = true;
				var loading = this.$loading({
					lock: true,
					text: '加载中,请稍后...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				vm.$http.post('http://localhost/act/taskInstance/getTaskFormsForView?processInstanceId=' + item.processInstanceId + "&&taskInstanceId=" + item.id).then(
					function(data) {
						loading.close()
						vm.hisFrmData = data.data.data;
						console.log(vm.hisFrmData)
					}).catch(function(error) {
					loading.close();
					//					console.log(error.response.status)
					//					if(error.response.status == 504){
					//						that.$message.error("网络超时，请重试")
					//					}

				});

				console.log(item)
				if(item.formKey != null) {
					var formName = item.formKey.split(",")
				}
				if(formName != undefined && formName.length != 0) {
					for(var i = 0; i < formName.length; i++) {
						vm.$http.get('http://localhost/activiti-web/activitiTemplate/' + formName[i] + "?processInstanceId=" + vm.processInstanceId + "&&taskInstanceId=" + vm.taskInstanceId).then(
							function(data) {
								console.log(data)
								var url = {};
								url.url = data.config.url;
								var ifraUrlstart = data.config.url.lastIndexOf('/');
								var ifraUrlend = data.config.url.indexOf('.');
								url.id = data.config.url.substring(ifraUrlstart + 1, ifraUrlend)
								vm.diaFormData.push(url)
								console.log(vm.diaFormData)
							}).catch(function(error) {
							loading.close();
							console.log(error.response.status)
							if(error.response.status == 504) {
								vm.$message.error("网络超时，请重试")
							}

						})
					}
				}
			},
			seeEnclosure() {
				var vm = this;
				this.$http.post('http://localhost/act/taskInstance/getTaskAttachments?processInstanceId=' + vm.processInstanceId + "&&taskId=" + vm.taskInstanceId).then(
					function(data) {
						console.log(data)
						vm.formUpload = data.data
					},
					function(error) {
						vm.$message.error(data.data.message);
					}
				);
				vm.uploadVisible = true;
			},
			load() {
				var vm = this;
				vm.$http.post('http://localhost/act/taskInstance/loadLastestTaskFormData/?processInstanceId=' + vm.processInstanceId + "&&taskInstanceId=" + vm.taskInstanceId).then(
					function(data) {
						console.log(data)
					},
					function(error) {
						vm.$message.error(data.data.message);
					}
				)
			},
			diaLoad(){
				var vm = this
				setTimeout(function() {
					$('#dialog-form iframe').each(function() {
						$(this).contents().find('body form input').attr("disabled", true)
						$(this).contents().find('body form select').attr("disabled", true)
						for(var i = 0; i < vm.hisFrmData.length; i++) {
							var id = vm.hisFrmData[i].formKey.indexOf('.');
							var iframrId = vm.hisFrmData[i].formKey.substring(0, id)
							if($(this).attr('id') == iframrId) {
//								var formeD = vm.hisFrmData[i].formData.split("&")
//								var obj = {};
//								for(var i = 0; i < formeD.length; i++) {
//									var arr = formeD[i].split('=');
//									obj[arr[0]] = arr[1];
//								}
                                var obj=JSON.parse(vm.hisFrmData[i].formData);
								for(var key in obj) {
									$(this).contents().find('body form input[name=' + key + ']').val(obj[key])
									$(this).contents().find('body form input[type=radio][name=' + key + ']').attr("checked", obj[key])
									$(this).contents().find('body form input[type=checkbox][name=' + key + ']').attr("checked", obj[key])
									$(this).contents().find('body form select[name=' + key + ']').val(obj[key])
								}
							}
						}
						$(this).height($(this).contents().find('body').height() + 20);
						
					})

				}, 500)
			},
			handleClose(done) {
				this.$confirm('确认关闭？')
					.then(_ => {
						done();
					})
					.catch(_ => {});
			},
		}
	}
</script>

<style>

</style>